<template>
  <div>
    <BusinessTable
      ref="businessTable"
      :search-params="searchParams"
      :table-columns="tableColumns"
      :page-query-url="pageQueryUrl"
      :custom-btn="customBtn"
      @custom-btn="customBtnClick"
    />
    <a-drawer title="添加数据模型信息" width="1200px" :visible="showDataDrawer0" :body-style="{ paddingBottom: '80px' }" :destroyOnClose="true" @close="closeDataDrawer0">
      <a-form-model :model="formData0" :rules="rules0" ref="ruleForm0" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-divider orientation="left"><span style="font-size: 14px; font-weight: bold;">模型信息</span></a-divider>
        <a-form-model-item label="表名" prop="name">
          <a-input v-model="formData0.name" placeholder="请输入表名"></a-input>
        </a-form-model-item>
        <a-form-model-item label="中文名" prop="nameZh">
          <a-input v-model="formData0.nameZh" placeholder="请输入中文名"></a-input>
        </a-form-model-item>
        <a-form-model-item label="描述" prop="comment">
          <a-input v-model="formData0.comment" placeholder="请输入描述"></a-input>
        </a-form-model-item>
        <a-form-model-item label="数据源" prop="dataSource">
          <a-select
            v-model="formData0.dataSource"
            placeholder="请选择数据源"
            show-search
            option-filter-prop="children"
            :filter-option="filterOption"
            :showArrow="false"
            @change="datasourceChange"
          >
            <a-select-option :value="item.name" v-for="(item, index) in datasource" :key="index">
              {{ item.name + '(' + item.comment + ')' }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-divider orientation="left"><span style="font-size: 14px; font-weight: bold;">模型字段信息</span></a-divider>
        <a-table :columns="columns" :data-source="data" bordered :pagination="false">
          <div slot="name" slot-scope="text, record, index"><a-input :value="text" @change="(e) => handleCellChange(e.target.value, 'name', index)"></a-input></div>
          <div slot="nameZh" slot-scope="text, record, index"><a-input :value="text" @change="(e) => handleCellChange(e.target.value, 'nameZh', index)"></a-input></div>
          <div slot="comment" slot-scope="text, record, index"><a-input :value="text" @change="(e) => handleCellChange(e.target.value, 'comment', index)"></a-input></div>
          <div slot="type" slot-scope="text, record, index">
            <a-select :value="text" @change="(e) => handleCellChange(e, 'type', index)">
              <a-select-option value="varchar">
                varchar
              </a-select-option>
              <a-select-option value="bigint">
                bigint
              </a-select-option>
              <a-select-option value="double">
                double
              </a-select-option>
              <a-select-option value="text">
                text
              </a-select-option>
              <a-select-option value="longtext">
                longtext
              </a-select-option>
              <a-select-option value="datetime">
                datetime
              </a-select-option>
            </a-select>
          </div>
          <div slot="length" slot-scope="text, record, index">
            <a-input-number :value="text" @change="(e) => handleCellChange(e, 'length', index)" :disabled="record.type !== 'varchar'"></a-input-number>
          </div>
          <div slot="action" slot-scope="text, record, index">
            <a @click="addLastRow(record, index)">向上方插入</a>
            <a style="margin: 0 8px;" @click="addNextRow(record, index)">下方插入</a>
            <a @click="deleteCurrentRow(record, index)">删除</a>
          </div>
        </a-table>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '10px' }" type="primary" @click="addDatatable">
          提交
        </a-button>
        <a-button @click="closeDataDrawer0">取消</a-button>
      </div>
    </a-drawer>
    <a-drawer title="修改数据模型信息" width="800px" :visible="showDataDrawer" :body-style="{ paddingBottom: '80px' }" :destroyOnClose="true" @close="closeDataDrawer">
      <a-form-model :model="formData" :rules="rules" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="表名" prop="name">
          <a-input v-model="formData.name" placeholder="请输入表名" :disabled="true"></a-input>
        </a-form-model-item>
        <a-form-model-item label="中文名" prop="nameZh">
          <a-input v-model="formData.nameZh" placeholder="请输入中文名"></a-input>
        </a-form-model-item>
        <a-form-model-item label="描述" prop="comment">
          <a-input v-model="formData.comment" placeholder="请输入描述"></a-input>
        </a-form-model-item>
        <a-form-model-item label="数据源" prop="dataSource">
          <a-input v-model="formData.dataSource" placeholder="请输入数据源" default-value="mysql" :disabled="true"></a-input>
        </a-form-model-item>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '10px' }" type="primary" @click="updateDataTable">
          提交
        </a-button>
        <a-button @click="closeDataDrawer">取消</a-button>
      </div>
    </a-drawer>
    <a-drawer title="编辑数据模型字段信息" width="1200px" :visible="showDataDrawer2" :body-style="{ paddingBottom: '80px' }" :destroyOnClose="true" @close="closeDataDrawer2">
      <BusinessTable
        ref="businessTable2"
        book-title="数据模型字段信息"
        :default-search-condition="defaultSearchCondition"
        :search-params="searchParams2"
        :table-columns="tableColumns2"
        :page-query-url="pageQueryUrl2"
        :custom-btn="customBtn2"
        @custom-btn="customBtnClick"
      />
    </a-drawer>
    <a-drawer :title="drawerTitle" width="800px" :visible="showDataDrawer3" :body-style="{ paddingBottom: '80px' }" :destroyOnClose="true" @close="closeDataDrawer3">
      <a-form-model :model="formData2" :rules="rules2" ref="ruleForm2" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="字段名" prop="name">
          <a-input v-model="formData2.name" placeholder="请输入表名" :disabled="fieldEdit"></a-input>
        </a-form-model-item>
        <a-form-model-item label="中文名" prop="nameZh">
          <a-input v-model="formData2.nameZh" placeholder="请输入中文名"></a-input>
        </a-form-model-item>
        <a-form-model-item label="注释" prop="comment">
          <a-input v-model="formData2.comment" placeholder="请输入注释"></a-input>
        </a-form-model-item>
        <a-form-model-item label="类型" prop="type">
          <a-select v-model="formData2.type" @change="handleChange">
            <a-select-option value="varchar">
              varchar
            </a-select-option>
            <a-select-option value="bigint">
              bigint
            </a-select-option>
            <a-select-option value="double">
              double
            </a-select-option>
            <a-select-option value="text">
              text
            </a-select-option>
            <a-select-option value="longtext">
              longtext
            </a-select-option>
            <a-select-option value="datetime">
              datetime
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="长度" prop="length">
          <a-input-number v-model="formData2.length" placeholder="请输入长度" style="width: 100%" :disabled="formData2.type !== 'varchar'"></a-input-number>
        </a-form-model-item>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '10px' }" type="primary" @click="addDataTableField" v-if="!fieldEdit">
          提交
        </a-button>
        <a-button :style="{ marginRight: '10px' }" type="primary" @click="updateDataTableField" v-else>
          提交
        </a-button>
        <a-button @click="closeDataDrawer3">取消</a-button>
      </div>
    </a-drawer>

    <a-modal title="数据模型生成" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
      <a-form-model :model="formData3" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules3" ref="ruleForm3">
        <a-form-model-item label="数据源" prop="dataSource">
          <a-select
            v-model="formData3.dataSource"
            placeholder="请选择数据源"
            show-search
            option-filter-prop="children"
            :filter-option="filterOption"
            :showArrow="false"
            @change="datasourceChange"
          >
            <a-select-option :value="item.name" v-for="(item, index) in datasource" :key="index">
              {{ item.name + '(' + item.comment + ')' }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="表名" prop="name">
          <a-select v-model="formData3.name" placeholder="请选择表名" show-search option-filter-prop="children" :filter-option="filterOption" :showArrow="false">
            <a-select-option :value="item" v-for="(item, index) in datatable" :key="index">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
  import BusinessTable from '@/components/BusinessTable';
  import { uuid } from 'vue-uuid';
  import { CUSTOM_BTN, CUSTOM_BTN2, RULES, RULES2, RULES3, SEARCH_PARAMS, SEARCH_PARAMS2, SYSTEM_FIELDS } from '@/views/datatable/index';
  export default {
    name: 'datatable',
    components: { BusinessTable },
    data() {
      return {
        fieldEdit: false,
        data: [
          {
            key: uuid.v4(),
            name: '',
            nameZh: '',
            comment: '',
            type: '',
            length: null,
          },
        ],
        columns: [
          {
            title: '字段名',
            dataIndex: 'name',
            key: 'name',
            scopedSlots: { customRender: 'name' },
          },
          {
            title: '中文名',
            dataIndex: 'nameZh',
            key: 'nameZh',
            scopedSlots: { customRender: 'nameZh' },
          },
          {
            title: '注释',
            dataIndex: 'comment',
            key: 'comment',
            scopedSlots: { customRender: 'comment' },
          },
          {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            width: 130,
            scopedSlots: { customRender: 'type' },
          },
          {
            title: '长度',
            dataIndex: 'length',
            key: 'length',
            scopedSlots: { customRender: 'length' },
          },
          {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            scopedSlots: { customRender: 'action' },
          },
        ],
        datasource: [],
        datatable: [],
        visible: false,
        confirmLoading: false,
        defaultSearchCondition: {},
        rules0: RULES,
        rules: RULES,
        rules2: RULES2,
        rules3: RULES3,
        formData0: {},
        formData: {},
        formData2: {},
        formData3: {},
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
        drawerTitle: null,
        searchParams: SEARCH_PARAMS,
        searchParams2: SEARCH_PARAMS2,
        tableColumns: [
          {
            title: '表名',
            dataIndex: 'name',
            key: 'name',
          },
          {
            title: '中文名',
            dataIndex: 'nameZh',
            key: 'nameZh',
          },
          {
            title: '描述',
            dataIndex: 'comment',
            key: 'comment',
          },
          {
            title: '数据源',
            dataIndex: 'dataSource',
            key: 'dataSource',
          },
          {
            title: '表信息',
            dataIndex: 'action',
            customRender: (text, record, index) => {
              return (
                <span class="action-col">
                  <a onClick={() => this.actionClick(record, index)}>修改</a>
                </span>
              );
            },
            slots: { title: 'action' },
          },
          {
            title: '字段信息',
            dataIndex: 'action2',
            customRender: (text, record, index) => {
              return (
                <span class="action-col">
                  <a onClick={() => this.actionClick2(record, index)}>编辑</a>
                </span>
              );
            },
            slots: { title: 'action' },
          },
          {
            title: '创建日期',
            dataIndex: 'creationDate',
            key: 'creationDate',
          },
          {
            title: '修改人',
            dataIndex: 'lastUpdatedBy',
            key: 'lastUpdatedBy',
          },
          {
            title: '修改日期',
            dataIndex: 'lastUpdateDate',
            key: 'lastUpdateDate',
          },
        ],
        tableColumns2: [
          {
            title: '字段名',
            dataIndex: 'name',
            key: 'name',
          },
          {
            title: '中文名',
            dataIndex: 'nameZh',
            key: 'nameZh',
          },
          {
            title: '注释',
            dataIndex: 'comment',
            key: 'comment',
          },
          {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
          },
          {
            title: '长度',
            dataIndex: 'length',
            key: 'length',
          },
          {
            title: '操作',
            dataIndex: 'action',
            customRender: (text, record, index) => {
              return (
                <span class="action-col">
                  <a onClick={() => this.actionClick3(record, index)}>编辑</a>
                </span>
              );
            },
            slots: { title: 'action' },
          },
          {
            title: '创建日期',
            dataIndex: 'creationDate',
            key: 'creationDate',
          },
          {
            title: '修改人',
            dataIndex: 'lastUpdatedBy',
            key: 'lastUpdatedBy',
          },
          {
            title: '修改日期',
            dataIndex: 'lastUpdateDate',
            key: 'lastUpdateDate',
          },
        ],
        pageQueryUrl: this.api.datatable.pageQueryDataTable,
        pageQueryUrl2: this.api.dataTableField.pageQueryDataTableField,
        customBtn: CUSTOM_BTN,
        customBtn2: CUSTOM_BTN2,
        nodeData: null,
        showDataDrawer0: false,
        showDataDrawer: false,
        showDataDrawer2: false,
        showDataDrawer3: false,
      };
    },
    created() {},
    watch: {
      data(curVal) {
        if (curVal.length === 0) {
          this.data = [
            {
              key: uuid.v4(),
              name: '',
              nameZh: '',
              comment: '',
              type: '',
              length: null,
            },
          ];
        }
      },
    },
    methods: {
      addDataTableField() {
        this.$refs.ruleForm2.validate((valid) => {
          if (valid) {
            this.axios.post(this.api.dataTableField.addDataTableField, this.formData2).then((res) => {
              if (res.code === 'ok') {
                this.$refs.businessTable2.reset();
                this.showDataDrawer3 = false;
              }
            });
          }
        });
      },
      updateDataTableField() {
        this.$refs.ruleForm2.validate((valid) => {
          if (valid) {
            this.axios.post(this.api.dataTableField.updateDataTableField, this.formData2).then((res) => {
              if (res.code === 'ok') {
                this.$refs.businessTable2.reset();
                this.showDataDrawer3 = false;
              }
            });
          }
        });
      },
      add2() {
        this.fieldEdit = false;
        this.formData2 = {};
        this.drawerTitle = '新增字段信息';
        this.showDataDrawer3 = true;
      },
      delete2() {
        if (this.$refs.businessTable2.selectedRowKeys.length === 0) {
          this.$message.warn('请至少选择一行数据');
          return;
        }

        const deleteArr = [];
        for (const index of this.$refs.businessTable2.selectedRowKeys) {
          deleteArr.push(this.$refs.businessTable2.tableData[index]);
        }
        this.axios.post(this.api.dataTableField.deleteDataTableField, deleteArr).then((res) => {
          if (res.code === 'ok') {
            this.$refs.businessTable2.reset();
          }
        });
      },
      addDatatable() {
        this.$refs.ruleForm0.validate((valid) => {
          if (valid) {
            const fields = [];
            for (const item of this.data) {
              const obj = { ...item };
              delete obj.key;
              fields.push(obj);
            }
            this.formData0.fields = fields;
            this.axios.post(this.api.datatable.addDataTable, this.formData0).then((res) => {
              if (res.code === 'ok') {
                this.$refs.businessTable.reset();
                this.showDataDrawer0 = false;
              }
            });
          }
        });
      },
      handleCellChange(val, key, index) {
        val = val ? val.trim().toLowerCase() : val;
        if (key === 'name') {
          //不允许包含系统字段
          if (SYSTEM_FIELDS.includes(val)) {
            this.$message.warn('不允许输入系统字段');
            return false;
          }
        }
        if (key === 'type' && val !== 'varchar') {
          this.data[index].length = null;
        }
        this.data[index][key] = val;
      },
      addLastRow(record, index) {
        const empty = {
          key: uuid.v4(),
          name: '',
          nameZh: '',
          comment: '',
          type: '',
          length: null,
        };
        this.data = [].concat(this.data.slice(0, index), empty, this.data.slice(index));
      },
      addNextRow(record, index) {
        const empty = {
          key: uuid.v4(),
          name: '',
          nameZh: '',
          comment: '',
          type: '',
          length: null,
        };
        this.data = [].concat(this.data.slice(0, index + 1), empty, this.data.slice(index + 1));
      },
      deleteCurrentRow(record, index) {
        this.data = [].concat(this.data.slice(0, index), this.data.slice(index + 1));
      },
      datasourceChange(value) {
        this.axios.get(this.api.datatable.showTables + '?datasourceName=' + value).then((res) => {
          if (res.code == 'ok') {
            this.datatable = res.data;
          }
        });
      },
      handleOk() {
        this.$refs.ruleForm3.validate((valid) => {
          if (valid) {
            this.axios.post(this.api.datatable.generateTable, this.formData3).then((res) => {
              if (res.code === 'ok') {
                this.$refs.businessTable.reset();
                this.visible = false;
              }
            });
          }
        });
      },
      handleCancel() {
        this.visible = false;
      },
      handleChange(value) {
        if (value !== 'varchar') {
          this.formData2.length = null;
        }
      },
      createDataTable() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.formData.url =
              'jdbc:mysql://' +
              this.formData.host +
              ':' +
              this.formData.port +
              '/' +
              this.formData.schemaName +
              '?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true';
            this.axios.post(this.api.datasource.addDatasource, this.formData).then((res) => {
              if (res.code === 'ok') {
                this.$refs.businessTable.reset();
                this.$message.success('添加成功');
                this.showDataDrawer = false;
              }
            });
          }
        });
      },
      updateDataTable() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.axios.post(this.api.datatable.updateDataTable, this.formData).then((res) => {
              if (res.code === 'ok') {
                this.$refs.businessTable.reset();
                this.showDataDrawer = false;
              }
            });
          }
        });
      },
      actionClick(record, index) {
        console.log(index);
        this.formData = record;
        this.showDataDrawer = true;
      },
      actionClick2(record, index) {
        console.log(index);
        this.formData = record;
        this.defaultSearchCondition = { tableId: record.id };
        this.showDataDrawer2 = true;
      },
      actionClick3(record, index) {
        console.log(index);
        this.fieldEdit = true;
        this.formData2 = record;
        this.drawerTitle = '修改字段信息';
        this.showDataDrawer3 = true;
      },
      closeDataDrawer0() {
        this.showDataDrawer0 = false;
      },
      closeDataDrawer() {
        this.showDataDrawer = false;
      },
      closeDataDrawer2() {
        this.showDataDrawer2 = false;
      },
      closeDataDrawer3() {
        this.showDataDrawer3 = false;
      },
      customBtnClick(code) {
        const func = this[code];
        func();
      },
      add() {
        this.formData0 = {};
        this.data = [];
        //查询可用数据源
        this.axios.get(this.api.datasource.queryAllDatasource).then((res) => {
          if (res.code === 'ok') {
            this.datasource = res.data;
            this.showDataDrawer0 = true;
          }
        });
      },
      generate() {
        this.formData3 = {};
        //查询可用数据源
        this.axios.get(this.api.datasource.queryAllDatasource).then((res) => {
          if (res.code === 'ok') {
            this.datasource = res.data;
            this.visible = true;
          }
        });
      },
      delete() {
        if (this.$refs.businessTable.selectedRowKeys.length === 0) {
          this.$message.warn('请至少选择一行数据');
          return;
        }

        const idList = [];
        for (const index of this.$refs.businessTable.selectedRowKeys) {
          idList.push(this.$refs.businessTable.tableData[index].id);
        }
        this.axios.post(this.api.datatable.deleteDataTable, idList).then((res) => {
          if (res.code === 'ok') {
            this.$refs.businessTable.reset();
          }
        });
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      },
    },
  };
</script>

<style scoped>
  /deep/ .ant-modal-footer div {
    display: flex;
    flex-direction: row-reverse;
  }
  /deep/ .ant-modal-footer .ant-btn {
    margin-left: 10px;
  }
</style>
